package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     *  新建菜品和菜品口味信息
     */
    @Transactional
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        // 1.保存菜品信息
        // 1.1 dishDto --> dish
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        // 1.2调用mapper完成新增菜品
        this.dishMapper.insert(dish);
        // 1.3拿到回写的id
        Long dishId = dish.getId();
        // 2.保存菜品的菜品口味信息
        // 2.1判断传入的信息是否有菜品口味的信息
        if(CollectionUtils.isNotEmpty(dishDTO.getFlavors())){
            // 给口味信息赋值
            // 赋值
            for (DishFlavor flavor : dishDTO.getFlavors()) {
                flavor.setDishId(dishId);
            }
            // 写入数据库中
            this.dishFlavorMapper.saveBatch(dishDTO.getFlavors());
        }
    }

    /**
     *  菜品分页查询
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        // 开启分页插件
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        // 调用mapper层查询
        Page<DishVO> page=dishMapper.pageQuery(dishPageQueryDTO);
        // 创建page对象
        PageResult pageResult = new PageResult();
        // 总记录数
        pageResult.setTotal(page.getTotal());
        // 每页记录
        pageResult.setRecords(page.getResult());
        return pageResult;
    }

    /**
     *  根据id批量删除
     */
    @Transactional
    @Override
    public void deleteByIds(List<Long> ids) {
        // 1.查看要删除的菜品是否是启售状态
        Integer startCount = dishMapper.getCountByIds(ids);
        if(startCount > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        // 2.判断菜品是否被套餐关联了
        Integer count=setmealDishMapper.getCountIdsByDishIds(ids);
        if (count > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 3.删除菜品
        dishMapper.deleteByIds(ids);
        // 4.删除菜品口味
        dishFlavorMapper.deleteByIds(ids);
    }

    /**
     *  根据id查询菜品信息
     */
    @Transactional
    @Override
    public DishVO getById(Long id) {
        // 调用mapper获取菜品信息
        Dish dish = dishMapper.getById(id);

        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);

        // 调用mapper层获取菜品口味
        List<DishFlavor> dishFlavor = dishFlavorMapper.getByDishId(id);

        dishVO.setFlavors(dishFlavor);
        return dishVO;
    }

    /**
     *  修改菜品信息
     */
    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        // 调用service层修改菜品信息
        dishMapper.update(dish);
        // 删除菜品原来的菜品口味
        List<Long> dishIds = Arrays.asList(dishDTO.getId());
        dishFlavorMapper.deleteByIds(dishIds);
        // 再次添加菜品口味
        if(CollectionUtils.isNotEmpty(dishDTO.getFlavors())){
            // 给口味信息赋值
            // 赋值
            for (DishFlavor flavor : dishDTO.getFlavors()) {
                flavor.setDishId(dishDTO.getId());
            }
            // 写入数据库中
            this.dishFlavorMapper.saveBatch(dishDTO.getFlavors());
        }
    }

    /**
     *  菜品启售停售
     */
    // TODO 待修改
    @Transactional
    @Override
    public void statusOrStop(Integer status, Long id) {
        // 将菜品属性封装为dish
        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.update(dish);

        // 如果是停售操作，还需要将包含当前菜品的套餐也停售
        if(status == StatusConstant.DISABLE){
            List<Long> ids = Arrays.asList(id);

            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
            if(CollectionUtils.isNotEmpty(setmealIds)){
                // 将菜品关联的套餐停售
                setmealMapper.updateStatus(status,setmealIds);
//                for (Long setmealId : setmealIds) {
//                    Setmeal setmeal = Setmeal.builder()
//                            .id(setmealId)
//                            .status(StatusConstant.DISABLE)
//                            .build();
//                    setmealMapper.update(setmeal);
//                }
            }
        }
    }

    /**
     *  根据分类id查询菜品
     */
    @Override
    public  List<Dish> getList(Long categoryId) {
        List<Dish> dish = dishMapper.getList(categoryId);
        return dish;
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.getList(dish.getCategoryId());

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
